package cn.lger.icollege.service;

import cn.lger.icollege.dao.AdminDao;
import cn.lger.icollege.dao.ClassRoomDao;
import cn.lger.icollege.dao.StudentDao;
import cn.lger.icollege.dao.TeacherDao;
import cn.lger.icollege.entity.Admin;
import cn.lger.icollege.entity.Classroom;
import cn.lger.icollege.entity.Student;
import cn.lger.icollege.entity.Teacher;
import cn.lger.icollege.util.excel.ExcelUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * Code that Changed the World
 * Pro said
 * Created by Pro on 2018-04-29.
 */
@Service
public class AdminService {

    @Resource
    private StudentDao studentDao;
    @Resource
    private ClassRoomDao classRoomDao;
    @Resource
    private TeacherDao teacherDao;
    @Resource
    private AdminDao adminDao;
    @Resource
    private PasswordEncoder encoder;


    @Transactional
    public void saveStudentsByExcel(File excel){
        String[] headers = {"学号", "姓名", "初始密码", "班级编号", "班级名称", "家庭住址", "联系电话"};

        try {
            ExcelUtil.readExcelDealRow(0, excel, headers, row -> {
                if (row.getPhysicalNumberOfCells() == 1)
                    return;
                Student student = new Student();
                student.setUsername(ExcelUtil.getCellValue(row.getCell(0)));
                student.setName(ExcelUtil.getCellValue(row.getCell(1)));
                student.setPassword(encoder.encode(ExcelUtil.getCellValue(row.getCell(2))));
                Optional<Classroom> optionalClassroom = classRoomDao.findById(Long.valueOf(ExcelUtil.getCellValue(row.getCell(3))));
                Classroom classroom;
                if (optionalClassroom.isPresent()){
                    classroom = optionalClassroom.get();
                }else {
                    classroom = new Classroom();
                    classroom.setClassId(Long.valueOf(ExcelUtil.getCellValue(row.getCell(3))));
                    classroom.setClassName(ExcelUtil.getCellValue(row.getCell(4)));
                    classRoomDao.save(classroom);
                }
                student.setClassroom(classroom);
                student.setAddress(ExcelUtil.getCellValue(row.getCell(5)));
                student.setPhone(ExcelUtil.getCellValue(row.getCell(6)));
                studentDao.save(student);
            });
        } catch (IOException | InvalidFormatException e) {
            throw new RuntimeException("文件处理失败");
        }
    }

    @Transactional
    public void saveTeachersByExcel(File excel) {
        String[] headers = {"教师编号", "姓名", "初始密码", "家庭住址", "联系电话"};

        try {
            ExcelUtil.readExcelDealRow(0, excel, headers, row -> {
                if (row.getPhysicalNumberOfCells() == 1)
                    return;
                Teacher teacher = new Teacher();
                teacher.setUsername(ExcelUtil.getCellValue(row.getCell(0)));
                teacher.setName(ExcelUtil.getCellValue(row.getCell(1)));
                teacher.setPassword(encoder.encode(ExcelUtil.getCellValue(row.getCell(2))));
                teacher.setAddress(ExcelUtil.getCellValue(row.getCell(3)));
                teacher.setPhone(ExcelUtil.getCellValue(row.getCell(4)));
                teacherDao.save(teacher);
            });
        } catch (IOException | InvalidFormatException e) {
            throw new RuntimeException("文件处理失败");
        }
    }

    public Admin findAdminByUsername(String username) {
        Optional<Admin> adminOptional = adminDao.findById(username);
        return adminOptional.orElse(null);
    }

    public Admin updateAdmin(Admin admin) {
        Optional<Admin> adminOptional = adminDao.findById(admin.getUsername());
        if (adminOptional.isPresent()){
            Admin temp = adminOptional.get();
            if (admin.getIconPath() != null){
                temp.setIconPath(admin.getIconPath());
            }
            if (admin.getPassword() != null && !"".equals(admin.getPassword().trim()))
                temp.setPassword(encoder.encode(admin.getPassword()));
            return adminDao.save(temp);
        }
        return null;
    }
}
